package com.suishoupai.xmb.controller;

import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.Location;
import com.suishoupai.xmb.entity.Xiaoqu;
import com.suishoupai.xmb.service.XiaoquService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Map;

/**
 * Created by caojian on 2017/3/30.
 */
@Controller
@RequestMapping("/xiaoqu")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class XiaoquController {
    @Autowired
    private XiaoquService xiaoquService;

    /**
     * 小区列表页面
     *
     * @param map
     * @param model
     * @return
     */
    @GetMapping("")
    public Object index(@RequestParam Map map, Model model) {
        PageUtil.startPage(map);
        Page page = (Page) xiaoquService.getAll();
        model.addAttribute("xiaoquList", page.toPageInfo());
        return "xiaoqu-list";
    }

    @GetMapping("/add")
    public Object addPage(Location location, Model model) {
        ValidateUtil.notNull(location.getLatitude());
        ValidateUtil.notNull(location.getLongitude());
        ValidateUtil.notNull(location.getName());
        model.addAttribute("location", location);
        return "xiaoqu-add";
    }


    /**
     * 增加小区
     *
     * @param xiaoqu
     * @return
     */
    @PostMapping("")
    public Object add(Xiaoqu xiaoqu) {
        xiaoquService.add(xiaoqu);
        return new ModelAndView(new RedirectView("/xiaoqu", true, false, true));
    }

    @GetMapping("/{xiaoquId}")
    public Object xiaoquEdit(@PathVariable("xiaoquId") long xiaoquId, Location location, Model model) {
        if (location.getLongitude() != null && location.getLatitude() != null) {
            Xiaoqu xiaoqu = new Xiaoqu();
            xiaoqu.setId(xiaoquId);
            xiaoqu.setName(location.getName());
            xiaoqu.setLatitude(location.getLatitude());
            xiaoqu.setLongitude(location.getLongitude());
            model.addAttribute("xiaoqu", xiaoqu);
            return "xiaoqu-edit";
        }
        model.addAttribute("xiaoqu", xiaoquService.getByXiaoquId(xiaoquId));
        return "xiaoqu-edit";
    }

    /**
     * 更新小区
     *
     * @param xiaoquId
     * @param xiaoqu
     * @return
     */
    @PostMapping("/{xiaoquId}")
    public Object update(@PathVariable("xiaoquId") long xiaoquId, Xiaoqu xiaoqu) {
        xiaoqu.setId(xiaoquId);
        xiaoquService.update(xiaoqu);
        return new ModelAndView(new RedirectView("/xiaoqu", true, false, true));
    }
}
